<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar
      title="编辑昵称"
      left-text="取消"
      right-text="确定"
      @click-left="$emit('close-popup')"
      @click-right="onCloseRight"
    ></van-nav-bar>
    <!-- 输入框 -->
    <van-field
      v-model="nickName"
      type="textarea"
      maxlength="7"
      placeholder="请输入新昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { updatetUserProfile } from '@/api/user.js'
export default {
  data () {
    return {
      nickName: ''
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  created () {
    this.nickName = this.value
  },

  methods: {
    async onCloseRight () {
      if (this.nickName.trim() === '') return this.$toast('请输入正确的昵称!')
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })
      try {
        await updatetUserProfile({
          name: this.nickName
        })
        this.$emit('close-popup')
        this.$emit('input', this.nickName)
        this.$toast.success('更新成功!')
      } catch (err) {
        if (err.response && err.response.status === 409) return this.$toast('昵称已存在!')
        this.$toast('更新失败!')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
